<template>
  <div class="animated fadeIn">
    <!-- 库存信息（货运中心） 2018/3/7 14:51 zhangQ -->
    <Row>
      <i-col :span="8">
        <addinventory :show="inventoryObj.addinventoryShow" :operaType="inventoryObj.operaType"
                      :inventory="inventoryObj.inventory"
                      @modalclose="inventoryObj.addinventoryShow = false,handleSearch()"></addinventory>
        <Button type="primary" size="large" @click="addProduct">
          <Icon type="ios-download-outline"></Icon>
          录入信息
        </Button>
        <Button type="primary" size="large" @click="exportDataInventory">
          <Icon type="ios-download-outline"></Icon>
          导出数据
        </Button>
      </i-col>
      <Form ref="searchForm" :model="searchForm" inline style="float: right;">
        <span style="line-height:32px;">电厂</span>
        <FormItem>
          <Select v-model="searchForm.userName" filterable placeholder="请输入电厂">
            <Option :value="所有电厂" :key="所有电厂">所有电厂</Option>
            <Option v-for="item in userNamelist" :value="item.userName" :key="item.userName">{{ item.userName }}
            </Option>
          </Select>
        </FormItem>
        <sapn class="lh-32">开始日期</sapn>
        <FormItem>
          <DatePicker format="yyyy年MM月dd日" :value="searchForm.startDateValue" v-model="searchForm.startDateValue"
                      placeholder="选择日期" style="width: 200px"></DatePicker>
        </FormItem>
        <sapn class="lh-32">结束日期</sapn>
        <FormItem>
          <DatePicker format="yyyy年MM月dd日" :value="searchForm.endtDateValue" v-model="searchForm.endtDateValue"
                      placeholder="选择日期" style="width: 200px"></DatePicker>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="handleSearch">查询</Button>
        </FormItem>
      </Form>
    </Row>
    <Row>
      <i-col :md="24">
        <div>
          <div style="position:relative; margin-top: 20px;">

            <Table :columns="columns7" :data="dealOrder(main_order_list)" ref="table" border no-data-text='无此数据'></Table>

            <div style="position:absolute;top:0px;width:100%;height:100%;display: flex;
                                      align-items: center;
                                      justify-content: center;background: rgba(210, 216, 222, 0.5);"
                 v-if="list_loadding">
              <Spin size="large"></Spin>
              <h6 style="color:#2d8cf0;margin-top:10px;">正在获取数据...</h6>
            </div>
          </div>

          <Page :total="this.pageTotal" show-total @on-change="setInitPage"
                style="text-align:right;margin-top:50px" show-elevator></Page>


        </div>


      </i-col>
      <i-col :md="12">
      </i-col>
    </Row>
  </div>
</template>
<script>
  import { getPowerStockList, getPowerUserList } from '@api/backEnd/inventory'
  import moment from 'moment'
  import { exportUtil } from '@/vendor/exportInvoke'
  import addinventory from './components/addInventory.vue'

  export default {
    name: 'inventoryInfoCenter',
    data () {
      let inventoryObj = {
        addinventoryShow: false,
        operaType: 'add',
        inventory: {
          startDateValue: moment().format('YYYY-MM-DD'),
          poweruserName: '',
          xhl: 0,
          kcl: 0,
          ddl: 0,
          lastQuarterDemand: 0,
          nextQuarterDemand: 0
        }
      }
      return {
        inventoryObj: inventoryObj,
        searchForm: {
          userName: '',
          startDateValue: moment().format('YYYY-MM-DD'),
          endtDateValue: moment().format('YYYY-MM-DD')
        },
        userNamelist: [],
        progresshow: false,
        progresscount: 0,
        progresstatus: 'active',
        progressspeed: 0,
        video_list: [],
        pageindex: 1,
        pageTotal: null,
        main_order_list: [],
        detailData: [],
        lodding: false,
        list_loadding: false,
        columns7: [
          {
            title: '电厂',
            key: 'userName'
          },
          {
            title: '日期',
            key: 'stockTime',
            render: (h, params) => {
              return h('span', moment(params.row.stockTime).format('YYYY-MM-DD'))
            }
          },
          {
            title: '昨日消耗量(万吨)',
            key: 'yesterdayConsume'
          },
          {
            title: '今日库存量(万吨)',
            ellipsis: 'false',
            key: 'nowStock'
          },
          {
            title: '安全库存(万吨)',
            ellipsis: 'false',
            render: (h, params) => {
              return h('span', ((+params.row.yesterdayConsume) * 7).toFixed(2))
            }
          },
          {
            title: '可耗用天数(天)',
            ellipsis: 'false',
            render: (h, params) => {
              if ((+params.row.yesterdayConsume)) {
                return h('span', ((+params.row.nowStock) / (+params.row.yesterdayConsume)).toFixed(1))
              } else {
                return h('span', '')
              }
            }
          },
          {
            title: '本季度需求(万吨)',
            ellipsis: 'false',
            key: 'lastQuarterDemand'
          },
          {
            title: '下季度需求(万吨)',
            ellipsis: 'false',
            key: 'nextQuarterDemand'
          },
          {
            title: '操作',
            key: 'action',
            align: 'center',
            render: (h, params) => {
              return h('div', [
                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      console.log(params.row.id)
                      this.editProduct(params.row)
                    }
                  }
                }, '修改')
              ])
            }
          }
        ]
      }
    },
    computed: {},
    methods: {
      /**
       * 导出电厂数据
       * */
      exportDataInventory () {
        let page = 1
        let stockStartTime = moment(this.searchForm.startDateValue).format('YYYY-MM-DD HH:mm:ss')
        let stockEndTime = moment(this.searchForm.endtDateValue).format('YYYY-MM-DD HH:mm:ss')
        let userName = this.userName
        let pageSize = 10000
        getPowerStockList({ page, stockStartTime, stockEndTime, userName, pageSize }).then(res => {
          if (res.data.isSuccess === 1) {
            let resDate = res.data.data.list
            let resColumns = JSON.parse(JSON.stringify(this.columns7))
            resColumns = resColumns.splice(0, resColumns.length - 1)
            let result = this.fasetJson(resDate)
            console.log('resColumns', resColumns)
            exportUtil.export2Excel('库存信息', result.columns, result.data)
          }
        })
      },
      /**
       * TODO(计算头表信息)
       * @param
       * @auther zhangQ
       * @date 2018/2/5 11:39
       **/
      fasetJson (tabData) {
        let result = {
          columns: [
            { title: '序号', key: 'num' },
            { title: '日期', key: 'stockTime' },
            { title: '企业名称', key: 'userName' },
            { title: '日耗煤量（万吨）', key: 'yesterdayConsume' },
            { title: '现有库存（万吨）', key: 'nowStock' },
            { title: '安全库存（万吨）', key: 'securityStorage' }, // 安全库存 = yesterdayConsume * 7
            { title: '可用天数', key: 'useDay' },
            { title: '本季度需求（万吨）', key: 'lastQuarterDemand' },
            { title: '下季度需求（万吨）', key: 'nextQuarterDemand' }
          ],
          data: []
        }
        let index = 0
        tabData.forEach((item) => {
          let useDay = (item.nowStock / item.yesterdayConsume).toFixed(1)
          if (useDay === 'Infinity') {
            useDay = ''
          }
          let securityStorage = ((+item.yesterdayConsume) * 7)
          let dataItem = {
            num: index + 1,
            stockTime: moment(item.stockTime).format('YYYY-MM-DD'),
            userName: item.userName,
            yesterdayConsume: (item.yesterdayConsume ? item.yesterdayConsume : 0).toFixed(2),
            nowStock: (item.nowStock ? item.nowStock : 0).toFixed(2),
            securityStorage: (securityStorage ? securityStorage : 0).toFixed(2),
            useDay: useDay,
            lastQuarterDemand: (item.lastQuarterDemand ? item.lastQuarterDemand : 0).toFixed(2),
            nextQuarterDemand: (item.nextQuarterDemand ? item.nextQuarterDemand : 0).toFixed(2)
          }
          result.data.push(dataItem)
          index++
        })
        return result
      },
      /**
       * TODO(添加录入信息)
       * @param
       * @auther zhangQ
       * @date 2018/2/3 22:52
       **/
      addProduct () {
        this.inventoryObj.operaType = 'add'
        this.inventoryObj.inventory = {
          startDateValue: moment().format('YYYY-MM-DD'),
          poweruserName: '',
          xhl: 0,
          kcl: 0,
          ddl: 0,
          lastQuarterDemand: 0,
          nextQuarterDemand: 0
        }
        this.inventoryObj.addinventoryShow = !this.inventoryObj.addinventoryShow
      },
      /**
       * TODO(编辑录入信息)
       * @param
       * @auther zhangQ
       * @date 2018/2/3 22:52
       **/
      editProduct (inventory) {
        this.inventoryObj.operaType = 'edit'
        this.inventoryObj.inventory = {
          id: inventory.id,
          startDateValue: moment(inventory.stockTime).format('YYYY-MM-DD'),
          poweruserName: inventory.userName,
          xhl: inventory.yesterdayConsume,
          kcl: inventory.yesterdayStock,
          ddl: inventory.yesterdayArrive,
          lastQuarterDemand: inventory.lastQuarterDemand,
          nextQuarterDemand: inventory.nextQuarterDemand
        }
        this.inventoryObj.addinventoryShow = !this.inventoryObj.addinventoryShow
      },
      remove (index) {
        this.video_list.splice(index, 1)
      },
      setInitPage (page) {
        this.pageindex = page
        let userName = this.searchForm.userName
        let stockStartTime = moment(this.searchForm.startDateValue).format('YYYY-MM-DD HH:mm:ss')
        let stockEndTime = moment(this.searchForm.endtDateValue).format('YYYY-MM-DD HH:mm:ss')
        var param = {}
        if (userName || userName !== '所有电厂') {
          param = { page, stockStartTime, stockEndTime, userName }
        } else {
          param = { page, stockStartTime, stockEndTime }
        }
        getPowerStockList(param).then(res => {
          if (res.data.isSuccess === 1 && res.data.data) {
            this.main_order_list = res.data.data.list
            this.pageTotal = res.data.data.total
          } else {
            this.main_order_list = []
          }
        })
      },
      handleSearch () {
        let userName = this.searchForm.userName
        if (userName === '所有电厂' || !userName) {
          userName = ''
        }
        this.setInitPage(1)
      },
      /**
       * TODO(处理运单数据)
       * @param
       * @auther zhangQ
       * @date 2018/2/8 16:10
       **/
      dealOrder (mainOrder) {
        let resMainOrder = []
        mainOrder.forEach((item) => {
          let itemClone = {
            yesterdayConsume: ((item.yesterdayConsume === 'null' || !+item.yesterdayConsume) ? 0 : +item.yesterdayConsume).toFixed(2),
            nowStock: ((item.nowStock === 'null' || !+item.nowStock) ? 0 : +item.nowStock).toFixed(2),
            lastQuarterDemand: ((item.lastQuarterDemand === 'null' || !+item.lastQuarterDemand) ? 0 : +item.lastQuarterDemand).toFixed(2),
            nextQuarterDemand: ((item.nextQuarterDemand === 'null' || !+item.nextQuarterDemand) ? 0 : +item.nextQuarterDemand).toFixed(2)
          }
          resMainOrder.push(Object.assign({}, item, itemClone))
        })
        return resMainOrder
      }
    },
    mounted () {
      const vue = this
      this.list_loadding = true
      setTimeout(function () {
        vue.list_loadding = false
      }, 2000)
      this.setInitPage(1)
      getPowerUserList().then(res => {
        if (res.data.isSuccess === 1) {
          this.userNamelist = res.data.data
        }
      })
    },
    watch: {
      'searchForm.userName': function (newVal, oldVal) {
        if (!newVal || newVal === '所有电厂') {
          this.searchForm.startDateValue = moment().subtract(1, 'days').format('YYYY-MM-DD')
          this.searchForm.endtDateValue = moment().format('YYYY-MM-DD')
        } else {
          this.searchForm.startDateValue = moment().subtract(6, 'days').format('YYYY-MM-DD')
          this.searchForm.endtDateValue = moment().format('YYYY-MM-DD')
        }
        this.handleSearch()
      }
    },
    components: { addinventory }
  }
</script>
<style scoped>

</style>
